package com.itheima.dao.impl;

import com.itheima.dao.AccountDao;
import com.itheima.po.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * ClassName:AccountDaoImpl
 * Package:com.itheima.dao.impl
 * Description:持久层的接口实现类
 * Date:2020/2/27 2:39
 * User: snow
 */
public class AccountDaoImpl2 implements AccountDao {

	private JdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public Account findAccountById(Integer accountId) {
		List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
		return accounts.isEmpty() ? null : accounts.get(0);
	}

	/**
	 * super  表示使用父类中的方法
	 *
	 * @param accountName
	 * @return
	 */
	public Account findAccountByName(String accountName) {
		List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
		if (accounts == null) {
			return null;
		}
		if (accounts.size() > 1) {
			throw new RuntimeException("结果集不唯一");
		}
		return accounts.get(0);
	}

	public void updateAccount(Account account) {
		jdbcTemplate.update("update account set name = ?, money = ? where id = ?", account.getName(), account.getMoney(), account.getId());
	}
}
